package com.hzgj.bcl.soa.collector;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/8/12.
 */
public class Collectors {

    private static Cache<CollectorKey, JmxCollector> cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build();
    private static final Logger logger = LoggerFactory.getLogger(Collectors.class);

    public static JmxCollector getCollector(String ip, int port) {
        try {
            return cache.get(new CollectorKey(ip, port), () -> {

                Map<String, Object> options = Maps.newHashMap();
                options.put("hostPort", ip + ":" + port);
                JmxCollector jmxCollector = new JmxCollector(options);
                jmxCollector.start();
                return jmxCollector;
            });
        } catch (ExecutionException e) {
            logger.error("{}", e);
        }
        return null;
    }

    public static void removeCollector(String ip, int port) {
        cache.invalidate(new CollectorKey(ip, port));
    }


    @AllArgsConstructor
    @Getter
    @ToString
    static class CollectorKey {
        private String ip;
        private int port;

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            CollectorKey that = (CollectorKey) o;
            return port == that.port &&
                    Objects.equals(ip, that.ip);
        }

        @Override
        public int hashCode() {
            return Objects.hash(ip, port);
        }
    }
}
